<?php
/**
 * 资金源判断
 * User: GRAY
 * Date: 16/8/11
 * Time: 下午10:23
 * 调用方法 BaseHook::executePayWayHook("PAYWAY_ENGINE_HOOK", $data,1);
 */

namespace Home\Common\Hook;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Log;


class PayWay extends BaseHook
{
    protected $secrect_key = '8183878756300635';
    protected $iv = '1861218900688990';
//     protected $server_url = 'http://123.57.22.1:9719'; //测试
    protected $server_url = 'http://www.labifenqi.com'; //正式

    public function execute($data, $params = []) {
//         echo '<pre>';
        $customerId = $data['id'];
        //$data['need_money']=200000;//单位元 测试写死 上线屏蔽
        if($customerId>0) {
            //51的用户不走玖富资金端
//             if($data['type']==1) {
//                 $data1['payway'] = 4;
//                 $orderId = $this->trade_no();
//                 $data['need_amount'] = ceil ($data['need_money']);
//                 $data = array(
//                   'order_id' => $orderId,
//                   'oid' => '',
//                   'customer_id' => $data['id'],
//                   'consume_id' => $data['consume_id'],
//                   'real_name' => $data['real_name'],
//                   'mobile' => $data['mobile'],
//                   'id_num' => $data['id_num'],
//                   'product'  => '找钱花3期分期',
//                   'product_id' => '',
//                   'money' => $data['need_amount'],
//                   'amount' => $data['need_money'],
//                   'payway' => 4,
//                   'plan_data'  => '',
//                   'status' => 1,
//                 );
//                 M('CustomerPaywayLog')->add($data);

//                 return $data1;
//             }

            if($data['birthplace']<>'') {
                //return;
                //获取银行卡
                $result = D("CustomerBankInfo")->query("SELECT `card_num`,`gate_id` FROM `customer_bank_info` WHERE `customer_id`='$customerId' AND `gate_id` in('BOC','ICBC','CMB','CCB','CMBC','CIB','CEB','ABC') and `sub_contract_id`<>'' limit 1");
                if($result) {
                    Log::borrow_write("****************资金端走玖富****************");
                    //资金端走玖富
                    $card_num = $result[0]['card_num'];
                    $gate_id = $result[0]['gate_id'];
                    if($card_num<>'' && $gate_id<>'') {
                        $data['card_num'] = $card_num;
                        $data['bankName'] = $gate_id;
                    }
                    //获取联系人
                    $data['contact_name1'] = '朵海云';
                    $data['contact_phone1'] = '18911306174';
                    $data['contact_name2'] = '王乾';
                    $data['contact_phone2'] = '15999635731';
                    $result_contact = D("CustomerContact")->query("SELECT `contact_name`,`contact_phone` FROM `customer_contact` WHERE `customer_id`='$customerId' AND `contact_name`<> '' and  CHAR_LENGTH(`contact_phone`) =11 AND  `contact_phone` LIKE  '1%' limit 2");
                    
                    
                    if($result_contact) {
                        $contact_name1 =  $result_contact[0]['contact_name'];
                        $contact_phone1 =  $result_contact[0]['contact_phone'];

                        $contact_name2 =  $result_contact[1]['contact_name'];
                        $contact_phone2 =  $result_contact[1]['contact_phone'];

                        if($contact_name1<>'' && $contact_phone1<>'') {
                            $data['contact_name1'] = $contact_name1;
                            $data['contact_phone1'] = $contact_phone1;
                        }
                        if($contact_name2<>'' && $contact_phone2<>'') {
                            $data['contact_name2'] = $contact_name2;
                            $data['contact_phone2'] = $contact_phone2;
                        }
                    }
                    
//                     print_r($data);exit;
                    $consume_id = $data['consume_id'];
                    if($consume_id >0) {
                        //默认值;正式环境PROD25338十一期PROD25339十七期
                        //测试环境PROD11366十一期,PROD11365十七期
                        //默认值;正式环境改为PROD25347十一期PROD2549十七期
                        $data['payway_product_id'] = 'PROD25369';
//                        $data['payway_product_id'] = 'PROD25339';
                        //$data['payway_product_id'] = 'PROD11366';
                        $data['payway_product'] = '找钱花11期分期';
                        $result = D()->query("SELECT b.`repay_times`,b.`id`,(SELECT `county_id` FROM `merchant` WHERE id = a.`merchant_id`) as county_id FROM  `consume_history` a LEFT JOIN  `sys_installment_plan` b ON b.`id` = a.`repay_id` WHERE a.`id` ='$consume_id'");
                        
                        if($result) {
                            $repay_times =  $result[0]['repay_times'];
                            //正式环境PROD23629九期 PROD24001十一期 PROD24002十七期
                            if($repay_times == 0 || $repay_times == 3 || $repay_times == 10) {
                                $data['payway_product_id'] = 'PROD25369';
                                $data['payway_product'] = '找钱花11期分期';
                            }
                            if($repay_times == 12) {
                                $data['payway_product_id'] = 'PROD25369';
                                $data['payway_product'] = '找钱花11期分期';
                            }
                       if($repay_times == 1) {
                                $data['payway_product_id'] = 'PROD25369';
                                $data['payway_product'] = '找钱花11期分期';
                            }
                            $county_id = $result[0]['county_id'];
                            //内蒙古
                            //SELECT  `county_id` FROM  `position_county` WHERE  `city_id` IN (SELECT  `city_id` FROM  `position_city` WHERE  `province_id` =150)
                            $county_nmg_arr = array("150102000000","150103000000","150104000000","150105000000","150121000000","150122000000","150123000000","150124000000","150125000000","150202000000","150203000000","150204000000","150205000000","150206000000","150207000000","150221000000","150222000000","150223000000","150302000000","150303000000","150304000000","150402000000","150403000000","150404000000","150421000000","150422000000","150423000000","150424000000","150425000000","150426000000","150428000000","150429000000","150430000000","150502000000","150521000000","150522000000","150523000000","150524000000","150525000000","150526000000","150581000000","150602000000","150621000000","150622000000","150623000000","150624000000","150625000000","150626000000","150627000000","150702000000","150703000000","150721000000","150722000000","150723000000","150724000000","150725000000","150726000000","150727000000","150781000000","150782000000","150783000000","150784000000","150785000000","150802000000","150821000000","150822000000","150823000000","150824000000","150825000000","150826000000","150902000000","150921000000","150922000000","150923000000","150924000000","150925000000","150926000000","150927000000","150928000000","150929000000","150981000000","152201000000","152202000000","152221000000","152222000000","152223000000","152224000000","152501000000","152502000000","152522000000","152523000000","152524000000","152525000000","152526000000","152527000000","152528000000","152529000000","152530000000","152531000000","152921000000","152922000000","152923000000");
                            //甘肃
                            $county_gs_arr = array('620102000000','620103000000','620104000000','620105000000','620111000000','620121000000','620122000000','620123000000','620201000000','620302000000','620321000000','620402000000','620403000000','620421000000','620422000000','620423000000','620502000000','620503000000','620521000000','620522000000','620523000000','620524000000','620525000000','620602000000','620621000000','620622000000','620623000000','620702000000','620721000000','620722000000','620723000000','620724000000','620725000000','620802000000','620821000000','620822000000','620823000000','620824000000','620825000000','620826000000','620902000000','620921000000','620922000000','620923000000','620924000000','620981000000','620982000000','621002000000','621021000000','621022000000','621023000000','621024000000','621025000000','621026000000','621027000000','621102000000','621121000000','621122000000','621123000000','621124000000','621125000000','621126000000','621202000000','621221000000','621222000000','621223000000','621224000000','621225000000','621226000000','621227000000','621228000000','622901000000','622921000000','622922000000','622923000000','622924000000','622925000000','622926000000','622927000000','623001000000','623021000000','623022000000','623023000000','623024000000','623025000000','623026000000','623027000000');
                            //从资金端多借钱
                            if($data['need_money'] >0 ){
//                                 $data['need_amount'] = ceil ($data['need_money'] * 1.3 * 1.4);
                                $data['need_amount'] = ceil ($data['need_money'] * 5 * 1.4);
                                if(in_array($county_id,$county_nmg_arr) && $county_id<>'') {
                                    //内蒙古分期多借 29%
                                    $data['need_amount'] = ceil ($data['need_money'] * 1.35 * 1.4);
                                }
                                if(in_array($county_id,$county_gs_arr) && $county_id<>'') {
                                    //甘肃分期多借 43%
                                    $data['need_amount'] = ceil ($data['need_money'] * 1.43 * 1.4);
                                }
                            }
                        }
                    }
                   //$ret = $this->fbank($data);
                    
                    if($ret) {
                        $data1['payway'] = 2;
                    } else {
                        //$data1['payway'] = 1;
                        BusinessException::throwException('不符合玖富蜡笔分期要求');
                    }
                } else {
                    Log::borrow_write("****************资金端走找钱花****************");

                    //资金端走找钱花
                    //$data1['payway'] = 1;
                    $consume_id = $data['consume_id'];
                    $repay_times='';
                    $result = D()->query("SELECT b.`repay_times`,b.`id`,(SELECT `county_id` FROM `merchant` WHERE id = a.`merchant_id`) as county_id FROM  `consume_history` a LEFT JOIN  `sys_installment_plan` b ON b.`id` = a.`repay_id` WHERE a.`id` ='$consume_id'");
                    if($result) {
                        $repay_times =  $result[0]['repay_times'];
                    }
                    $orderId = $this->trade_no();
                    $data['need_amount'] = ceil ($data['need_money'] * 1.3);
                    $data = array(
                      'order_id' => $orderId,
                      'oid' => '',
                      'customer_id' => $data['id'],
                      'consume_id' => $data['consume_id'],
                      'real_name' => $data['real_name'],
                      'mobile' => $data['mobile'],
                      'id_num' => $data['id_num'],
                      'product'  => '找钱花分期',
                      'product_id' => $repay_times,
                      'money' => $data['need_amount'],
                      'amount' => $data['need_money'],
                      'payway' => 3,
                      'plan_data'  => '',
                      'status' => 4,
                    );
                    M('CustomerPaywayLog')->add($data);

                    BusinessException::throwException('用户没有绑定有效的银行卡');
                }
            } else {
                //资金端走找钱花
                //$data1['payway'] = 1;
                BusinessException::throwException('身份证住址为空');
            }
        } else {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }
        return $data1;

/*
        $id_num = $data['id_num'];
        $age_pass = $data['age_pass'];
        if($age_pass==1) {
            return $data;
        }
        if ($id_num) {
            $userAge = D("Customer")->getAgeById($id_num);
            //Log::write("Customer contact:".$contactCount, Log::INFO);
            if ($userAge < $params['min'] || $userAge > $params['max']) {
                //暂不操作
                //BusinessException::throwException(Constant::INVALID_AGE);
            }
        }
BOC	中国银行股份有限公司
ICBC	中国工商银行股份有限公司
CMB	招商银行股份有限公司
CCB	中国建设银行股份有限公司
PSBC	中国邮政储蓄银行有限责任公司 （不支持）
CMBC	中国民生银行股份有限公司
CIB	兴业银行股份有限公司
CEB	中国光大银行股份有限公司
目前支持：建设银行,农业银行,中国银行,中信银行,光大银行,兴业银行,浦发银行,工商银行,民生银行,广发银行,平安银行,招商银行,交通银行
*/
       
    }

    //玖富蜡笔分期
    public function fbank($data) {

        //$data['mobiel']='15900738112';
        Log::write("资金端引擎请求数据: ".json_encode($data), Log::INFO);
        Log::borrow_write("****************资金端引擎请求数据****************".json_encode($data));

        $serviceToken = $this->getServiceToken();//获取接入权限
        if($serviceToken) {
            $userToken = $this->getUserToken($data,$serviceToken);//获取用户token
        }
        if($userToken) {
            $ret = $this->checkId($data,$userToken); //查询身份证是否注册
            //print_r($this->queryOrganInfo($data,$userToken)); exit;//机构产品查询
            if($ret) {
                //未注册
                $ret = $this->saveUserInfo1($data,$userToken); //录入身份信息
                $ret = $this->saveUserInfo2($data,$userToken); //录入身份类型
                $ret = $this->saveUserInfo3($data,$userToken); //录入工作信息
                $ret = $this->saveUserInfo4($data,$userToken); //录入联系人信息
                $ret = $this->saveUserInfo5($data,$userToken); //录入其他信息
            }
            $ret = $this->queryBankInfo($data,$userToken); //银行卡信息查询
            if(!$ret) {
                //未绑定
                $ret = $this->saveBankInfo($data,$userToken); //绑定银行卡
                //$ret = $this->queryBankBindStatus($data,$userToken); //查询银行卡绑定状态(绑定中也可以下单)
            }
            //$ret = $this->queryUserInfoStatus($data,$userToken); exit;//资料审核状态查询（不通过审核也可以下单）
            //$ret = $this->checkCommitUserLoanInfo($data,$userToken); //用户下单验证接口（项目选择判断提示） //下单前不需要验证，会返回054资料不完善，1分钟后返回000
            /*
            if($ret) {
                //$result = $this->commitUsersLoanInfo($data,$userToken); //用户下单
            }*/
            Log::borrow_write("****************用户下单****************");

            $result = $this->commitUsersLoanInfo($data,$userToken); //用户下单
            Log::borrow_write("****************用户下单返回结果：".json_encode($result)."****************");
            if($result['loanId']>0) {
                $ret = $this->queryFRetMonPlanByLoanId($data,$userToken,$result['loanId']); //还款计划列表查询 需要入库
                $plan_data = json_encode($ret);
                //$need_money = $data['need_money'] + $data['need_money']*0.1; //借款多借10%
                $data = array(
                  'order_id' => $result['orderId'],
                  'oid' => $result['loanId'],
                  'customer_id' => $data['id'],
                  'consume_id' => $data['consume_id'],
                  'real_name' => $data['real_name'],
                  'mobile' => $data['mobile'],
                  'id_num' => $data['id_num'],
                  'product'  => $data['payway_product'],
                  'product_id' => $data['payway_product_id'],
                  'money' => $data['need_amount'],
                  'amount' => $data['need_money'],
                  'payway' => 2,
                  'plan_data'  => $plan_data,
                  'status' => 1,
                );
                M('CustomerPaywayLog')->add($data);
                //print_r($ret);
                //入库
                //echo $result['orderId'];
            }
        }
        return $data;
    }

    //获取接入权限
    protected function getServiceToken() {
//         $url = $this->server_url."/gatewayserver/tokenControl/getServiceToken";
        $url = $this->server_url."/api/userInfoEntry/getServiceToken";
        
        $post_arr = array(
//          'keyName'=>'092C7E6B680072F67ED6F4E5C71C61B8',
//          'appID'=>'295C7319DDCE7137A26C436DBCC22E8F',
//          'secret'=>'AA817A1E3D42B7F422021768AC646F37',
            
        'keyName'=>'C7E2A55AA7418036274C6FEF65B71AC0',
        'appID'=>'3DF9C158507950705DFCBBC13C179D2A',
        'secret'=>'7DD05C7C758C64867D9AAB8FAD9948C2',
        );
        
        $result = $this->post($url,$post_arr);
        $serviceToken = $result['serviceToken'];
        return $serviceToken;
    }

    //获取用户token
    protected function getUserToken($data,$serviceToken) {
        //$url = $this->server_url."/gatewayserver/tokenControl/getUserToken";
        $url = $this->server_url."/api/userInfoEntry/getUserToken";
        
        $post_arr = array(
            'appID'=>'3DF9C158507950705DFCBBC13C179D2A',
//             'appID'=>'295C7319DDCE7137A26C436DBCC22E8F',
            'serviceToken'=>$serviceToken,
            'accreditPhone'=>$data['mobile'],
            'entranceID'=>'24',
        );
        
        $result = $this->post($url,$post_arr);
        $userToken = $result['userToken'];
        
        if($userToken) {
            return $userToken;
        } else {
            BusinessException::throwException('获取用户token'.$result['respCode'].' '.$result['respMesg']);
        }
    }

    //身份证是否注册
    protected function checkId($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/checkId";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'userToken'=>$userToken,
            'idNum'=>$data['id_num'],
        );
        
        $result = $this->post($url,$post_arr);
        //$ret = ($result['respCode']=='079') ? true : false;
        Log::write("测试查看身份证信息请求数据: ".json_encode($result), Log::INFO);
        
        if($result['respCode']=='079') {
            return true; //身份证不存在 可以继续注册
        }elseif($result['respCode']=='078') 
            return false;
        else {
            BusinessException::throwException('身份证是否注册:'.$result['respCode'].' '.$result['respMesg']);
        }
    }

    //录入身份信息
    protected function saveUserInfo1($data,$userToken) {
        
        $birthplace_substr = mb_substr($data['birthplace'],0,25,'utf-8');
//      $url = $this->server_url."/api/userInfoEntry/saveUserInfo";
        $url = $this->server_url."/api/userInfoEntry/saveUserInfo";
        
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'idName'=>$data['real_name'],
            'idNum'=>$data['id_num'],
            'addr'=>$birthplace_substr,
            'addrDetail'=>$birthplace_substr,
            'locationiden'=>$data['birthplace'],
            'locationidenDetail'=>$data['birthplace'],
            'serverName'=>'SAVEIDEINFO',
        );
        
        $result = $this->post($url,$post_arr);
        Log::write("测试查看身份证信息返回数据: ".json_encode($result), Log::INFO);
        
        $result1 = json_decode($result['baseResp'][0]['respJson'],true);
        $ret = ($result['trafficStatus']=='SUCCESS' && $result1['respCode']=='066') ? true : false;
        
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('录入身份信息:'.$result1['respCode'].' '.$result1['respMesg']);
        }
    }

    //录入身份类型
    protected function saveUserInfo2($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/saveUserInfo";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'userType'=>'2',
            'serverName'=>'SAVEUSERTYPE',
        );
        $result = $this->post($url,$post_arr);
        $result1 = json_decode($result['baseResp'][0]['respJson'],true);
        $ret = ($result['trafficStatus']=='SUCCESS' && $result1['respCode']=='000') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('录入身份类型:'.$result1['respCode'].' '.$result1['respMesg']);
        }
    }

    //录入工作信息
    protected function saveUserInfo3($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/saveUserInfo";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'workAddrName'=>'无',
            'workPhone'=>'010-88888888',
            'workAddr'=>'无',
            'workPos'=>'无',
            'workLong'=>'1',
            'workStartDate'=>date('Y-m-d H:i:s',time()),
            'uinRec'=>'1',
            'monthIncome'=>'1',
            'workIndication'=>'0',
            'serverName'=>'SAVEWORKINFO'
        );
        $result = $this->post($url,$post_arr);
        $result1 = json_decode($result['baseResp'][0]['respJson'],true);
        $ret = ($result['trafficStatus']=='SUCCESS' && $result1['respCode']=='070') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('录入工作信息:'.$result1['respCode'].' '.$result1['respMesg']);
        }
    }

    //录入联系人信息
    protected function saveUserInfo4($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/saveUserInfo";
        $contact_name1 = ($data['contact_name1']<>'') ? $data['contact_name1'] : '';
        $contact_phone1 = ($data['contact_phone1']<>'') ? $data['contact_phone1'] : '';
        $contact_name2 = ($data['contact_name2']<>'') ? $data['contact_name2'] : '';
        $contact_phone2 = ($data['contact_phone2']<>'') ? $data['contact_phone2'] : '';

        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'relShip1'=>'7',
            'phone1'=>$contact_phone1,
            'name1'=>$contact_name1,
            'workAddr1'=>'',
            'relShip2'=>'7',
            'phone2'=>$contact_phone2,
            'name2'=>$contact_name1,
            'workAddr2'=>'',
            'relShip3'=>'7',
            'phone3'=>'',
            'name3'=>'',
            'workAddr3'=>'',
            'serverName'=>'SAVELINKINFO'
        );
        $result = $this->post($url,$post_arr);
        $result1 = json_decode($result['baseResp'][0]['respJson'],true);
        $ret = ($result['trafficStatus']=='SUCCESS' && $result1['respCode']=='072') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('录入联系人信息:'.$result1['respCode'].' '.$result1['respMesg']);
        }
    }

    //录入其他信息
    protected function saveUserInfo5($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/saveUserInfo";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'email'=>$data['mobile'].'@qq.com',
            'qq'=>$data['mobile'],
            'weiXinNo'=>'',
            'serverName'=>'SAVEOTHERINFO'
        );
        $result = $this->post($url,$post_arr);
        $result1 = json_decode($result['baseResp'][0]['respJson'],true);
        $ret = ($result['trafficStatus']=='SUCCESS' && $result1['respCode']=='074') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('录入其他信息:'.$result1['respCode'].' '.$result1['respMesg']);
        }
    }

/*
BOC	中国银行股份有限公司
ICBC	中国工商银行股份有限公司
CMB	招商银行股份有限公司
CCB	中国建设银行股份有限公司
PSBC	中国邮政储蓄银行有限责任公司 （不支持）
CMBC	中国民生银行股份有限公司
CIB	兴业银行股份有限公司
CEB	中国光大银行股份有限公司
目前支持：建设银行,农业银行,中国银行,中信银行,光大银行,兴业银行,浦发银行,工商银行,民生银行,广发银行,平安银行,招商银行,交通银行
*/
    //绑定银行卡
    protected function saveBankInfo($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/saveBankInfo";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'cardNo'=>$data['card_num'],
            'bankName'=>$data['bankName'],
            'cardProv'=>'北京',
            'cardCity'=>'北京',
        );
        $result = $this->post($url,$post_arr);
        $ret = ($result['respCode']=='076') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('绑定银行卡:'.$result['respCode'].' '.$result['respMesg']);
        }
    }

    //查询银行卡绑定状态
    protected function queryBankBindStatus($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/queryBankBindStatus";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
        );
        $result = $this->post($url,$post_arr);
        print_r($result);
        $ret = ($result['respCode']=='000' && $result['alwaysBankBindStatus']=='B1') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('查询银行卡绑定状态:'.$result['respCode'].' '.$result['respMesg']);
        }
    }

    //银行卡信息查询
    protected function queryBankInfo($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/queryBankInfo";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
        );
        $result = $this->post($url,$post_arr);
        $ret = ($result['respCode']=='000' && $result['cardNo']<>'') ? true : false;
        
        return $ret;
    }
/*
//身份信息查询 不需要调用
$url = $this->server_url."/api/userInfoEntry/getUserInfo";
$post_arr = array(
    'loginPhone'=>'18634364997',
    'chanType'=>'',
    'entranceID'=>'22',
    'reqTime'=>date('Y-m-d H:i:s',time()),
    'userToken'=>'8728a903bd6e4c1cb2d01895eb0af285',
);
*/

    //资料审核状态查询
    protected function queryUserInfoStatus($data,$userToken) {
        $url = $this->server_url."/api/userInfoEntry/queryUserInfoStatus";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
        );
        $result = $this->post($url,$post_arr);
        $ret = ($result['appStatus']=='2') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('资料审核状态查询:'.$result['respCode'].' '.$result['respMesg']);
        }
    }

    //机构编码 ORG11207
    //机构信息查询
    protected function queryOrgListInfo($data,$userToken) {
        $url = $this->server_url."/api/OrgEntry/queryOrgListInfo";
        $post_arr = array(
            'chanType'=>'',
            'entranceID'=>'24',
            'orgCode'=>'ORG11207',
            
        );
        
        $result = $this->post($url,$post_arr);
        
        $ret = ($result['respCode']=='10001') ? $result : false;
        return $ret;
    }

    //机构信息查询
    protected function queryOrganInfo($data,$userToken) {
        $url = $this->server_url."/api/OrgEntry/queryOrganInfo";
        $post_arr = array(
            'orgSource'=>'hysd001',//hysd001
            'orgCode'=>'ORG11207',
    
        );
    
        $result = $this->post($url,$post_arr);
    
        $ret = ($result['respCode']=='10001') ? $result : false;
        return $ret;
    }
    
/*
//机构信息查询 不需要
$url = $this->server_url."/api/OrgEntry/queryOrgListInfo";
$post_arr = array(
    'chanType'=>'',
    'entranceID'=>'22',
    'orgSource'=>'fenqingb',
);

    [fistAmt] => 100
    [increaseAmt] => 1
    [nper] => 9
    [price] => 0
    [prodName] => 花呗（9+0+0）
    [productCode] => PROD11318
    [totalAmount] => 10000
*/

    //用户下单验证接口（项目选择判断提示）
    protected function checkCommitUserLoanInfo($data,$userToken) {
        $url = $this->server_url."/api/OrderEntry/checkCommitUserLoanInfo";
        $prodCode = $data['payway_product_id'];//测试环境 PROD11318九期 PROD11333十四期 //正式环境PROD23629九期
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'prodCode'=>$prodCode,
        );
        $result = $this->post($url,$post_arr);
        $ret = ($result['respCode']=='000') ? true : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('用户下单验证接口:'.$result['respCode'].' '.$result['respMesg']);
        }
    }

    //用户下单
    protected function commitUsersLoanInfo($data,$userToken) {
        $url = $this->server_url."/api/OrderEntry/commitUsersLoanInfoFqb";
        $orderId = $this->trade_no();
        $prodCode = $data['payway_product_id'];//测试环境 PROD11318九期 PROD11333十四期  //正式环境PROD23629九期 PROD24001十一期 PROD24002十七期
        $loanMoney = ceil($data['need_amount']/100); //多借10% 转成元
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'orderId'=>$orderId,
            'loanMoney'=>$loanMoney, //单位元
            'prodCode'=>$prodCode
        );
        
        $result = $this->post($url,$post_arr);
        Log::borrow_write("****************用户下单：url：".$url."****************");
        Log::borrow_write("****************用户下单：请求数据：".json_encode($post_arr)."****************");
        Log::borrow_write("****************用户下单：返回数据：".json_encode($result)."****************");
        $ret = ($result['respCode']=='000') ? array('loanId'=>$result['loanId'],'orderId'=>$orderId) : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('用户下单:'.$result['respCode'].' '.$result['respMesg']);
        }
    }

/*
//订单查询接口 不需要
$url = $this->server_url."/api/OrderEntry/queryOrderInfo";
$post_arr = array(
    'loginPhone'=>'18634364997',
    'chanType'=>'',
    'entranceID'=>'22',
    'reqTime'=>date('Y-m-d H:i:s',time()),
    'userToken'=>'8728a903bd6e4c1cb2d01895eb0af285',
    'prodType'=>'1',
    'loanStatus'=>'0',
);
*/

    //还款计划列表查询 需要入库 //81972
    protected function queryFRetMonPlanByLoanId($data,$userToken,$loanId) {
        $url = $this->server_url."/api/OrderEntry/queryFRetMonPlanByLoanId";
        $post_arr = array(
            'loginPhone'=>$data['mobile'],
            'chanType'=>'',
            'entranceID'=>'24',
            'reqTime'=>date('Y-m-d H:i:s',time()),
            'userToken'=>$userToken,
            'loanId'=>$loanId,
        );
        
        
        $result = $this->post($url,$post_arr);
        $ret = ($result['respCode']=='000') ? $result : false;
        if($ret) {
            return $ret;
        } else {
            BusinessException::throwException('还款计划列表查询:'.$result['respCode'].' '.$result['respMesg']);
        }
    }
    //订单号生成
    public function trade_no() {
        list($usec, $sec) = explode(" ", microtime());
        $usec = substr(str_replace('0.', '', $usec), 0 ,4);
        $str  = rand(10,99);
        return date("ymdHis").$usec.$str;
    }

    public function post($url,$post_arr) {

        $post_data = json_encode($post_arr);
        $post_data = $this->encrypt($post_data);

        $ch=curl_init($url); 
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $response = curl_exec($ch);
        if(curl_errno($ch))
        {
            print curl_error($ch);
        }
        curl_close($ch);
        //echo $response;
        $result = $this->decrypt($response);
        $result_arr = json_decode($result,true);
        //echo "<pre>";
        //print_r($result);
        //print_r($result_arr);
        return $result_arr;
    }

    /**
     * 加密方法
     * @param string $str
     * @return string
     */
    public function encrypt($str){
        //AES, 128 ECB模式加密数据
        $screct_key = $this->secrect_key;
        //$screct_key = base64_decode($screct_key);
        $str = trim($str);
        $str = $this->addPKCS7Padding($str);
        //$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
        $encrypt_str =  mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC, $this->iv);
        return base64_encode($encrypt_str);
    }
      
    /**
     * 解密方法
     * @param string $str
     * @return string
     */
    public function decrypt($str){
        //AES, 128 ECB模式加密数据
        $screct_key = $this->secrect_key;
        $str = base64_decode($str);
        //$screct_key = base64_decode($screct_key);
        //$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
        $encrypt_str =  mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC, $this->iv);
        $encrypt_str = trim($encrypt_str);
        $encrypt_str = $this->stripPKSC7Padding($encrypt_str);
        return $encrypt_str;
    }
      
    /**
     * 填充算法
     * @param string $source
     * @return string
     */
    function addPKCS7Padding($source){
        $source = trim($source);
        $block = mcrypt_get_block_size('rijndael-128', 'cbc');
        $pad = $block - (strlen($source) % $block);
        if ($pad <= $block) {
            $char = chr($pad);
            $source .= str_repeat($char, $pad);
        }
        return $source;
    }
    /**
     * 移去填充算法
     * @param string $source
     * @return string
     */
    function stripPKSC7Padding($source){
        $block = mcrypt_get_block_size('tripledes', 'cbc');
        $char = substr($source, -1, 1);
        $num = ord($char);
        if($num > 8){
            //return $source;
        }
        $len = strlen($source);
        for($i = $len - 1; $i >= $len - $num; $i--){
            if(ord(substr($source, $i, 1)) != $num){
                return $source;
            }
        }
        $source = substr($source, 0, -$num);
        return $source;
    }
} 
